
import sqlite3

def escape_mysql_value(val):
    if val is None:
        return 'NULL'
    if isinstance(val, (int, float)):
        return str(val)
    # 空字符串转为0（仅用于整型/布尔型字段，后续可扩展类型判断）
    if val == '':
        return '0'
    # 字符串加单引号并转义
    return "'" + str(val).replace("'", "''") + "'"

conn = sqlite3.connect('db.sqlite3')
conn.row_factory = sqlite3.Row
cur = conn.cursor()

# 获取所有表名
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
tables = [row[0] for row in cur.fetchall()]

with open('db_export_utf8.sql', 'w', encoding='utf-8') as f:
    for table in tables:
        cur.execute(f'SELECT * FROM `{table}`')
        rows = cur.fetchall()
        if not rows:
            continue
        columns = [f'`{col}`' for col in rows[0].keys()]
        for row in rows:
            values = [escape_mysql_value(row[col]) for col in row.keys()]
            sql = f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES({', '.join(values)});\n"
            f.write(sql)
conn.close()